package com.citrix.gs.util;

import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.citrix.gs.util.beacon.BeaconCI;
import com.citrix.gs.util.beacon.Repository;
import com.citrix.gs.util.common.CIInfo;

public class RepositoryCleaner {
    
    private static Logger logger = LoggerFactory.getLogger(RepositoryCleaner.class);
    
    private Repository repo;
    private BeaconCI ci;
    
    public RepositoryCleaner(){
        
    }

    public BeaconCI getCi() {
        return ci;
    }

    public RepositoryCleaner setCi(BeaconCI ci) {
        this.ci = ci;
        return this;
    }
    
    public RepositoryCleaner setCIInfo(CIInfo ciInfo) {
        this.ci = new BeaconCI(ciInfo);
        return this;
    }

    public Repository getRepo() {
        return repo;
    }

    public RepositoryCleaner setRepo(Repository repo) {
        this.repo = repo;
        return this;
    }
    
    public void clean() {
        clean(this.repo);
    }
    
    public void clean(Repository repo) {
        clean(repo.getName());
    }

    public void clean(String name) {
        clean(Arrays.asList(name)); //TODO: optimize it as a single case
    }
    
    public void clean(List<String> nameList) {
        // Get job names 
        List<String> jobNames = ci.getJobNames(nameList);
        if(jobNames == null) {
            logger.error("No job found for names: %s ", nameList);
            return;
        }

        jobNames.stream().forEach(jobName -> {
            
            logger.info("Clean job: {}", jobName);
            try {
                ci.deleteJob(jobName, false);
            } catch (Exception e) {
                logger.error("Fail to delete job {}", jobName, e);
            }
        });

    }
}
